<template>
  <div>
    <div class="ccui-app-container">
      <div class="ccui-advanced-search-wrapper ccui-clearfix">
        <el-search
          ref="search"
          :formProp="formData"
          @search="search"
          :isShowSearch="isShowSearch"
          class="ccui-highsearch"
          :selectClear="true"
        >
          <anchorTitle
            isList
            :totalNum="totalNum"
            :tabBtn="tableTopBtn"
            :isFocus="isFocus"
            @tabBtnChange="tableTopChange"
          />
          <template slot="search">
            <el-input
              v-model="formData.contractName"
              clearable
              searchLabel="合同名称"
              placeholder="请输入合同名称模糊查询"
              @blur="handleTrim('contractName')"
            ></el-input>
            <el-input
              v-model="formData.partyBName"
              clearable
              searchLabel="供应商1"
              placeholder="请输入供应商1模糊查询"
              @blur="handleTrim('partyBName')"
            ></el-input>
            <el-input
              v-model="formData.contractCode"
              clearable
              searchLabel="合同编号"
              placeholder="请输入合同编号模糊查询"
              @blur="handleTrim('contractCode')"
            ></el-input>
            <el-input
              v-model="formData.partyBNameBak"
              clearable
              searchLabel="供应商2"
              placeholder="请输入供应商2模糊查询"
              @blur="handleTrim('partyBNameBak')"
            ></el-input>
            <el-input
              v-model="formData.reportInOrgName"
              clearable
              searchLabel="填报单位"
              placeholder="请输入填报单位模糊查询"
              @blur="handleTrim('reportInOrgName')"
            ></el-input>
            <el-date-picker
              v-model="formData.compileDate"
              type="date"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              searchLabel="编制日期"
              placeholder="请选择编制日期查询"
              slot="searchItem6"
            >
            </el-date-picker>
            <el-input
              v-model="formData.partyAName"
              clearable
              searchLabel="合同签订单位(甲方)"
              placeholder="请输入合同签订单位(甲方)模糊查询"
              @blur="handleTrim('partyAName')"
            ></el-input>
            <el-input
              v-model="formData.thirdCategoriesOfName"
              clearable
              searchLabel="分类名称"
              placeholder="请输入分类名称模糊查询"
              @blur="handleTrim('thirdCategoriesOfName')"
            ></el-input>
            <!-- <el-select
              class="ccui-form-longInput"
              v-model="formData.searchState"
              searchLabel="合同状态"
              placeholder="请选择合同状态查询"
              clearable
            >
              <el-option
                v-for="item in jsList.protocolState"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select> -->
          </template>
          <!-- 表单高级搜索 -->
          <el-input
            v-model="formData.contractName"
            clearable
            searchLabel="合同名称"
            placeholder="请输入合同名称模糊查询"
            slot="searchItem1"
            @blur="handleTrim('contractName')"
          ></el-input>
          <el-input
            v-model="formData.partyBName"
            clearable
            searchLabel="供应商1"
            placeholder="请输入供应商1模糊查询"
            slot="searchItem2"
            @blur="handleTrim('partyBName')"
          ></el-input>
          <el-input
            v-model="formData.contractCode"
            clearable
            searchLabel="合同编号"
            placeholder="请输入合同编号模糊查询"
            slot="searchItem3"
            @blur="handleTrim('contractCode')"
          ></el-input>
          <el-input
            v-model="formData.partyBNameBak"
            clearable
            searchLabel="供应商2"
            placeholder="请输入供应商2模糊查询"
            slot="searchItem5"
            @blur="handleTrim('partyBNameBak')"
          ></el-input>
          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
            slot="searchItem6"
            @blur="handleTrim('reportInOrgName')"
          ></el-input>
          <el-date-picker
            v-model="formData.compileDate"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            searchLabel="编制日期"
            placeholder="请选择编制日期查询"
            slot="searchItem7"
          >
          </el-date-picker>
          <el-input
            v-model="formData.partyAName"
            clearable
            searchLabel="合同签订单位(甲方)"
            placeholder="请输入合同签订单位(甲方)模糊查询"
            slot="searchItem8"
            @blur="handleTrim('partyAName')"
          ></el-input>
          <el-input
            v-model="formData.thirdCategoriesOfName"
            clearable
            searchLabel="分类名称"
            placeholder="请输入分类名称模糊查询"
            slot="searchItem9"
            @blur="handleTrim('thirdCategoriesOfName')"
          ></el-input>
          <!-- <el-select
            class="ccui-form-longInput"
            v-model="formData.searchState"
            searchLabel="合同状态"
            placeholder="请选择合同状态查询"
            slot="searchItem10"
            clearable
          >
            <el-option
              v-for="item in jsList.protocolState"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select> -->
        </el-search>
      </div>
      <!-- table表格 -->
      <div class="ccui-multifunctional-table-wrapper">
        <el-table
          v-if="tableHack"
          ref="multipleTable"
          :data="tableData"
          :fit="true"
          :row-style="rowClass"
          :cell-style="cellStyle"
          @cell-click="cellClick"
          border
          class="ccui-multifunctional-table"
          @selection-change="handleSelectionChange"
          @header-dragend="tableTitleWidth"
          :min-height="9999"
        >
          <template v-for="(table, index) in tableTheadOptions">
            <el-table-column
              v-if="table.checked"
              :fixed="table.fixed || false"
              :type="table.type"
              :key="index"
              :label="table.label"
              :min-width="table.width"
              :prop="table.prop"
              :filters="table.filters"
              :align="table.align"
              :header-align="table.headerAlign || 'left'"
              :show-overflow-tooltip="true"
            ></el-table-column>
          </template>

          <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-if="['5', '8', '9'].includes(scope.row.protocolState)"
                size="mini"
                type="text"
                @click="handleGoNew(scope.row)"
                >补充协议</el-button
              >
              <el-button
                v-if="['4', '6', '12'].includes(scope.row.protocolState)"
                size="mini"
                type="text"
                @click="handleEditor(scope.row)"
                >编辑</el-button
              >
              <el-button
                v-if="['4', '12'].includes(scope.row.protocolState)"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-button
                v-if="scope.row.protocolState == 3"
                size="mini"
                type="text"
                @click="handleTurn(scope.row)"
                >撤回</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="ccui-table-footer" v-if="totalNum > 0">
          <div id="ccui-paging">
            <el-pagination
              :total="totalNum"
              :page-size="getLocalPageSize()"
              :current-page="formDataSearch.pageNo"
              :page-sizes="[10, 20, 50, 100, 200, 500]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              popper-class="ccui-paging-page-size-popper"
              @prev-click="handlePrev"
              @next-click="handleNext"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <el-button
              class="ccui-pagination-btn"
              size="mini"
              type="default"
              @click="handleChangeSize('none')"
              >确定</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import jsList from "../js";
import anchorTitle from "@/basa/components/public/anchorTitle";
import {
  getAgreementList,
  getAgreementTurn,
  getAgreementDelete
} from "../api/";
import { setSessionItem, getSessionItem } from "@/basa/utils";

export default {
  name: "contractAgreement",
  components: { anchorTitle },
  props: {},
  data() {
    return {
      jsList,
      isActive: 0,
      // 表格数据
      tableData: [],
      tableHack: true,
      // 表格命名
      tableName: this.tableList.eqContractAgreement,
      // 表格数据
      tableThead: [],

      //全部数量
      totalNum: 0,
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      popoverShow: false,
      selectRow: [],
      selectData: [],
      // 高级搜索数据 start
      // 高级搜索提交数据
      isShowSearch: true,
      formData: {
        reportOrgId: getSessionItem("userInfo", "orgId"),
        contractName: "",
        contractCode: "",
        partyBName: "",
        partyBNameBak: "",
        compileDate: "",
        partyAName: "",
        thirdCategoriesOfName: "",
        searchState: "",
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        isShowPageLoading: true
      },
      formDataSearch: {
        reportOrgId: getSessionItem("userInfo", "orgId"),
        contractName: "",
        contractCode: "",
        partyBName: "",
        partyBNameBak: "",
        compileDate: "",
        partyAName: "",
        thirdCategoriesOfName: "",
        searchState: "",
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        isShowPageLoading: true
      },
      pageNo: 1,
      pageSize: 10,
      // 表格顶部按钮
      tableTopBtn: [
        { label: "全部", value: "" },
        { label: "待提交", value: "2" },
        { label: "审批中", value: "3" },
        { label: "审批退回", value: "6" }
      ],
      isFocus: "",
      // 高级搜索数据 end
      approvalFlow: true
    };
  },
  computed: {},
  created() {},
  mounted() {
    // this.initData();
    // this.getAgreementList(this.formData);
  },
  activated() {
    this.initData();
    this.getAgreementList(this.formData);
  },
  watch: {},
  methods: {
    //去空格
    handleTrim(key) {
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    },
    initData() {
      this.setTableWidth();
      this.renderTable();
    },
    // 列表数据请求
    getAgreementList(data) {
      getAgreementList(data).then(res => {
        if (res.data.code == 0) {
          this.tableData = res.data.data.rows;
          this.tableData.forEach(item => {
            item.protocolStateStr = jsList.protocolState.find(
              _ => _.value == item.protocolState
            ).label;

            if (item.compileDate) {
              item.compileDate = item.compileDate.substring(0, 10);
            }
            if (
              item.initTotalContractPriceIncludeTax ||
              item.initTotalContractPriceIncludeTax === 0
            ) {
              item.initTotalContractPriceIncludeTax = Number(
                item.initTotalContractPriceIncludeTax
              ).toFixed(2);
            }
          });
          this.totalNum = res.data.data.recordsTotal;
        }
      });
    },
    //撤回
    handleTurn(row) {
      this.$confirm("确定要撤回吗?", "提示信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          getAgreementTurn({
            concId: row.id,
            proConId: row.protocolId ? row.protocolId : ""
          }).then(res => {
            if (res.data.code == 0) {
              this.$message({
                message: "撤回成功",
                type: "success",
                showClose: true,
                ccuiCustom: true,
                duration: 8000
              });
              this.getAgreementList(this.formDataSearch);
            }
          });
        })
        .catch(() => {});
    },
    //删除
    handleDelete(row) {
      this.$confirm("确定要删除吗?", "提示信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          getAgreementDelete({ proConId: row.protocolId }).then(res => {
            if (res.data.code == 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                showClose: true,
                ccuiCustom: true,
                duration: 8000
              });
              this.getAgreementList(this.formDataSearch);
            }
          });
        })
        .catch(() => {});
    },
    // 详情
    goDetail(row) {
      this.$router.push({
        path: "/contractManagement/equipmentContractAgreement/item-detail",
        query: {
          concId: row.id,
          protocolId: row.protocolId
        }
      });
    },
    //新增补充协议
    handleGoNew(row) {
      this.$router.push({
        path: "/contractManagement/equipmentContractAgreement/item-add",
        query: { concId: row.id, newAdd: 1 }
      });
    },
    //编辑
    handleEditor(row) {
      this.$router.push({
        path: "/contractManagement/equipmentContractAgreement/item-edit",
        query: { concId: row.id, protocolId: row.protocolId }
      });
    },
    // 分页
    // 上一页
    handlePrev() {},
    // 下一页
    handleNext() {},
    //  显示条数更改
    handleSizeChange(val) {
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.pageSize = val;
      setSessionItem("pageSize", this.tableName, val);
      this.getAgreementList(this.formDataSearch);
    },
    //翻页确定
    handleChangeSize() {
      this.getAgreementList();
    },
    // 当前页码更改
    handleCurrentChange(val) {
      // 跳转翻页都会调这个方法
      this.formDataSearch.pageNo = val;
      this.getAgreementList(this.formDataSearch);
    },
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      this.formDataSearch.reportOrgId = getSessionItem("userInfo", "orgId");
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.isShowPageLoading = true;
      this.formDataSearch.pageSize = this.getLocalPageSize();
      this.getAgreementList(this.formDataSearch);
    },

    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "transparent" };
      }
      if (columnIndex == 1) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },
    // 查看
    cellClick(row, column, columnIndex) {
      if (["contractCode"].includes(column.property)) {
        this.goDetail(row);
      }
    },

    handleSelectionChange(data) {
      this.selectData = data;
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = jsList.fixedTableThead.concat(
        jsList.unfixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          localTableData.forEach(item => {
            let index = jsList.unfixedTableThead.findIndex(
              cItem => item.prop === cItem.prop
            );
            index !== -1 &&
              (jsList.unfixedTableThead[index].checked = item.checked);
          });
        } else {
          // 长度相同但值不同
          this.tableThead = jsList.fixedTableThead.concat(
            jsList.unfixedTableThead
          );
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = jsList.fixedTableThead.concat(
          jsList.unfixedTableThead
        );
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < jsList.unfixedTableThead.length; i++) {
        if (jsList.unfixedTableThead[i].label === column.label) {
          jsList.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = jsList.unfixedTableThead.concat(jsList.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.tableHack = false;
      this.$nextTick(() => {
        this.tableHack = true;
      });
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 顶部按钮切换
    tableTopChange({ value }) {
      this.isFocus = value;
      this.protocolState = value;
      this.resetFormData();
      this.formDataSearch.protocolState = value;
      console.log(this.formDataSearch);
      this.getAgreementList(this.formDataSearch);
    },
    // 获取默认条数
    getLocalPageSize() {
      return (
        getSessionItem("pageSize", this.tableList.eqContractAgreement) || 10
      );
    },
    // 重置表单
    resetFormData() {
      this.formDataSearch = {
        reportOrgId: getSessionItem("userInfo", "orgId"),
        contractName: "",
        contractCode: "",
        partyBName: "",
        partyBNameBak: "",
        compileDate: "",
        partyAName: "",
        thirdCategoriesOfName: "",
        searchState: "",
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        isShowPageLoading: true
      };
      setSessionItem("pageNo", this.tableName, {
        pageNo: 1,
        searchForm: {}
      });
      this.pageNo = 1;
      this.pageSize = 10;
    }
  }
};
</script>

<style scoped lang="scss">
/deep/.ccui-advanced-search-wrapper
  .el-search
  .el-searchs-bottom
  .el-form-item
  .el-form-item__label {
  min-width: 126px !important;
}
</style>
